const busDB = require('../../util/busDB'),
  log = require('../../util/log'),
  SQL_FIELDS = ['id', 'url', 'service'];

exports.select = (obj, resolve, reject) => {
  resolve = resolve || (() => {
  });
  reject = reject || (() => {
  });
  var sql = 'select * from url where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  busDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      reject(err)
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = url => {
  url.service_id = url.service
  delete url.service
  url.getService = function (resolve) {
    if (!!this.service) {
      resolve(this.service);
      return
    }
    serviceDao.select({
      id: this.service_id
    }, svcs => {
      this.service = svcs[0]
      resolve(this.service)
      if (svcs.length > 1)
        log(this.service_id + '对应多个服务')
    })
  }
}
